//
//  Tab2ViewController.m
//  SITABLE
//
//  Created by songjun on 16/9/18.
//  Copyright © 2016年 Sita. All rights reserved.
//

#import "Tab2ViewController.h"

@interface Tab2ViewController ()

@end

@implementation Tab2ViewController
{
    UITextField *inputMeterTf;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedStringFromTable(@"Safe", @"InfoPlist", nil);
    
    _locationManager = [[AMapLocationManager alloc]init];
    _locationManager.delegate = self;
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    if (!self.mapView) {
        self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - SCREEN_HEIGHT*.2+20)];
        self.mapView.delegate = self;
        [self.mapView setZoomLevel:15.1 animated:YES];
        
        [self.view addSubview:self.mapView];
    }
    [_locationManager startUpdatingLocation];
    
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow1:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide1:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    
    
    //若为00点,则以自己位置为中心画圆
    [self loadBotomView];
    
}





-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    [_mapView setVisibleMapRect:self.circle.boundingMapRect edgePadding:UIEdgeInsetsMake(10, 20, 140, 20) animated:YES];
}


- (void)mapView:(MAMapView *)mapView didLongPressedAtCoordinate:(CLLocationCoordinate2D)coordinate
{
    //长按地图设置一个范围
    [_mapView removeOverlay:self.circle];
    self.mySelfpointAnnotaiton.coordinate =coordinate;
    
    self.circle = [MACircle circleWithCenterCoordinate:coordinate  radius:[inputMeterTf.text doubleValue]];
    
    //在地图上添加圆
    [_mapView addOverlay: self.circle];
   
}

-(void)isSetSwitchAction:(UISwitch *)swith
{
    UILabel *lineLabel = [self.view viewWithTag:9002];
    if (swith.isOn) {
        //NSLog(@"开启");
        //        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:nil message:@"确定要开启围栏?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        //        alertview.tag = 790;
        //        [alertview show];
        lineLabel.hidden = NO;
        inputMeterTf.userInteractionEnabled = YES;
    }else{
        lineLabel.hidden = YES;
        inputMeterTf.userInteractionEnabled = NO;
        //NSLog(@"关闭");
        //        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:nil message:@"确定要关闭围栏?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        //        alertview.tag = 790;
        //        [alertview show];
        
    }
}


-(void)locateMySelfBtnAction:(UIButton *)btn
{
    [self.mapView setCenterCoordinate:[self.isMeAnnotation coordinate] animated:YES];
    _mySelfpointAnnotaiton.coordinate = self.isMeAnnotation.coordinate;
    [_mapView removeOverlay:self.circle];
    
    
    self.circle = [MACircle circleWithCenterCoordinate:self.isMeAnnotation.coordinate  radius:500];
    //在地图上添加圆
    [_mapView addOverlay: self.circle];
    
}




-(void)loadBotomView
{
    //初始化地图上定位自己的点
    UIButton *locateMySelfBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    locateMySelfBtn.frame =  CGRectMake(SCREEN_WIDTH-10-40, SCREEN_HEIGHT-SCREEN_HEIGHT*.25-70-64-49, 40, 40);
    [locateMySelfBtn setBackgroundImage:[UIImage imageNamed:@"locateBike"] forState:UIControlStateNormal];
    [locateMySelfBtn addTarget:self action:@selector(locateMySelfBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:locateMySelfBtn];
    
    self.botomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-SCREEN_HEIGHT*.25-64-49, SCREEN_WIDTH, SCREEN_HEIGHT*.25)];
    
    UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, 120, 35)];
    infoLabel.text = @"围栏功能开启";
    infoLabel.textColor = UIColorHexRGBA(linBoardNavitagionColor, 1.0);
    [self.botomView addSubview:infoLabel];
    
    //开关按钮
    UISwitch *isSetSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-15-80, 15, 80, 35)];
    
    if (SCREEN_WIDTH< 375) {
        isSetSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-15-80, 5, 80, 35)];
        infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-15-80, 5, 120, 35)];
        
    }
    isSetSwitch.tag = 191;
    [self.botomView addSubview:isSetSwitch];
    [isSetSwitch addTarget:self action:@selector(isSetSwitchAction:) forControlEvents:UIControlEventValueChanged];
    
    isSetSwitch.on = YES;
   
    
    //NSLog(@"哈哈哈:%d",_userElecFence.isweilan);
    self.botomView.backgroundColor = [UIColor whiteColor];
    UILabel *infonLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, (SCREEN_HEIGHT*.25)/2-30/2-10, 120, 30)];
    infonLabel.text = @"围栏设置范围";
    infonLabel.textColor = UIColorHexRGBA(linBoardNavitagionColor, 1.0);
    [self.botomView addSubview:infonLabel];
    
    UILabel *meterLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-15-30, (SCREEN_HEIGHT*.25)/2-30/2-10, 30, 30)];
    meterLabel.textAlignment = NSTextAlignmentRight;
    meterLabel.textColor = UIColorHexRGBA(linBoardNavitagionColor, 1.0);;
    meterLabel.text = @"米";
    [self.botomView addSubview:meterLabel];
    
    inputMeterTf = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-45-90, (SCREEN_HEIGHT*.25)/2-30/2-10, 90, 30)];
    inputMeterTf.keyboardType = UIKeyboardTypePhonePad;
    inputMeterTf.textColor = UIColorHexRGBA(linBoardNavitagionColor, 1.0);
    inputMeterTf.tag = 99;
    inputMeterTf.font = [UIFont systemFontOfSize:14];
    
    inputMeterTf.text = @"500";
    

    [inputMeterTf setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    inputMeterTf.textAlignment = NSTextAlignmentCenter;
    [self.botomView addSubview:inputMeterTf];
    
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-45-90,(SCREEN_HEIGHT*.25)/2-30/2-10+29, 90, 1)];
    lineLabel.tag = 9002;
    lineLabel.backgroundColor = UIColorHexRGBA(linBoardNavitagionColor, 1.0);
    [self.botomView addSubview:lineLabel];
    
    
    
    inputMeterTf.userInteractionEnabled = YES;
    lineLabel.hidden = NO;
    

    
    UIButton *shezhiBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shezhiBtn.frame = CGRectMake(15, self.botomView.frame.size.height-30-30, SCREEN_WIDTH-30, 40);
    [shezhiBtn addTarget:self action:@selector(shezhiBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    shezhiBtn.layer.cornerRadius = 5.0;
    [shezhiBtn setTitle:@"设    置" forState:UIControlStateNormal];
    [shezhiBtn setBackgroundColor:UIColorHexRGBA(linBoardNavitagionColor, 1.0)];
    [self.botomView addSubview:shezhiBtn];
    [self.view addSubview:self.botomView];
}


-(void)remove999Hud
{
    MBProgressHUD *mbhud = [self.view viewWithTag:999];
    if (mbhud) {
        [mbhud removeFromSuperview];
    }
}

-(void)shezhiBtnAction:(UIButton *)btn
{
    //20000
    //NSLog(@"设置了多少米:%d",[inputMeterTf.text intValue]);
    
    UISwitch *mySwich = [self.view viewWithTag:191];
    if (!mySwich.on) {
        MBProgressHUD *mbhud = [[MBProgressHUD alloc] initWithView:self.view];
        mbhud.mode = MBProgressHUDModeText;
        mbhud.tag = 999;
        [self.view addSubview:mbhud];
        mbhud.labelText = @"请开启围栏功能!";
        [mbhud show:YES];
        [self performSelector:@selector(remove999Hud) withObject:self afterDelay:1.5f];
        return;
    }
    
    
    if ([inputMeterTf.text intValue] > 20000) {
        MBProgressHUD *mbhud = [[MBProgressHUD alloc] initWithView:self.view];
        mbhud.mode = MBProgressHUDModeText;
        mbhud.tag = 999;
        [self.view addSubview:mbhud];
        mbhud.labelText = @"请输入小于20公里的围栏范围!";
        [mbhud show:YES];
        [self performSelector:@selector(remove999Hud) withObject:self afterDelay:1.5f];
        
    }else{
        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:nil message:@"确定要设置围栏?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alertview.tag = 789;
        [alertview show];
        
    }
    
    
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (alertView.tag == 789) {
        if (buttonIndex == 1) {
            
            MBProgressHUD *mbhud = [[MBProgressHUD alloc] initWithView:self.view];
            mbhud.mode = MBProgressHUDModeText;
            mbhud.tag = 999;
            [self.view addSubview:mbhud];
            mbhud.labelText = @"围栏设置成功!";
            [mbhud show:YES];
            [self performSelector:@selector(remove999Hud) withObject:self afterDelay:1.5f];
            [_mapView removeOverlay:self.circle];
            
            int radius =[inputMeterTf.text floatValue];
            
            if (radius == 0) {
                radius=500;
            }

            self.circle = [MACircle circleWithCenterCoordinate:self.mySelfpointAnnotaiton.coordinate radius:radius];
            
            //在地图上添加圆
            [_mapView addOverlay: self.circle];
            
            
           
    }

    }
}

-(void)removeHudAfter
{
    MBProgressHUD *mbhud = [self.view viewWithTag:607];
    [mbhud removeFromSuperview];
}


//当键盘出现或改变时调用
- (void)keyboardWillShow1:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    float duaration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    CGSize kbSize=[[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;
    int height = kbSize.height-64-49;
    
    [UIView animateWithDuration:duaration animations:^{
        self.view.frame = CGRectMake(0, -height, SCREEN_WIDTH, SCREEN_HEIGHT);
    }];
}

//当键退出时调用
- (void)keyboardWillHide1:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    float duaration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView animateWithDuration:duaration animations:^{
        self.view.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT);
    }];
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewDidAppear:YES];
    [inputMeterTf resignFirstResponder];
    
    
}



- (void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate
{
    [inputMeterTf resignFirstResponder];
}


- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
{
    if (!self.isMeAnnotation) {
        self.isMeAnnotation = [[MAPointAnnotation alloc] init];
        self.isMeAnnotation.title = @"isMeAnnotation";
        [self.mapView addAnnotation:self.isMeAnnotation];
        [_locationManager stopUpdatingLocation];
        //[_mapView setCenterCoordinate:location.coordinate animated:YES];
    }
    self.isMeAnnotation.coordinate = location.coordinate;
    
    
          if (!self.mySelfpointAnnotaiton) {
            self.mySelfpointAnnotaiton = [[MAPointAnnotation alloc] init];
            self.mySelfpointAnnotaiton.title = @"mySelf";
            [self.mapView addAnnotation:self.mySelfpointAnnotaiton];
            [self.mapView setCenterCoordinate:location.coordinate animated:YES];
            //构造圆
            self.circle = [MACircle circleWithCenterCoordinate:location.coordinate  radius:500];
            
            //在地图上添加圆
            [_mapView addOverlay: self.circle];
        }
        self.mySelfpointAnnotaiton.coordinate = location.coordinate;
    
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MACircle class]])
    {
        
        
        MACircleRenderer *circleRenderer = [[MACircleRenderer alloc] initWithCircle:overlay];
        circleRenderer.lineWidth   = 3.f;
        circleRenderer.strokeColor = UIColorHexRGBA(linBoardNavitagionColor, 0.8);
        circleRenderer.fillColor = UIColorHexRGBA(linBoardNavitagionColor, .3);
        [self performSelector:@selector(updateRangeMap) withObject:nil afterDelay:1.5f];
        return circleRenderer;
    }
    return nil;
}

-(void)updateRangeMap
{
     [_mapView setVisibleMapRect:self.circle.boundingMapRect edgePadding:UIEdgeInsetsMake(10, 20, 140, 20) animated:YES];
    [inputMeterTf resignFirstResponder];
}


- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    static NSString *reuseIndetifier = @"userCurrentLocationAnnotation";
    MAAnnotationView *annotationView = (MAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
    annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
    
    if ([[annotation title] isEqualToString:@"mySelf"])
    {
        
        annotationView.frame = CGRectMake(0, 0, 53, 53);
        annotationView.image = [UIImage imageNamed:@"myself"];
        annotationView.canShowCallout = NO;
        // 设置中心点偏移，使得标注底部中间点成为经纬度对应点
        annotationView.centerOffset = CGPointMake(0, -18);
    }else{
        annotationView.image = [UIImage imageNamed:@"carLocation"];
        annotationView.canShowCallout = NO;
        annotationView.centerOffset = CGPointMake(0, -18);
    }
    
    return annotationView;;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}




@end
